import '../models/generated_content.dart';
import '../services/api_service.dart';

class ContentGenerator {
  String? _currentProductId;
  String? _cachedDescription;
  int _contentIndex = 0;
  
  void setProductId(String productId) {
    if (_currentProductId != productId) {
      _currentProductId = productId;
      _cachedDescription = null;
      _contentIndex = 0;
    }
  }

  Future<GeneratedContent> generateSingleContent() async {
    if (_currentProductId == null) {
      throw Exception('Product ID not set. Call setProductId() first.');
    }
    
    try {
      // 每次都获取新的推广词，不做缓存和分割
      final description = await ApiService.getProductDescription(_currentProductId!);
      
      print('[ContentGenerator] 获取到推广词，长度: ${description.length}');
      print('[ContentGenerator] 内容: ${description.length > 100 ? description.substring(0, 100) + '...' : description}');
      
      // 如果描述为空，返回默认内容
      if (description.isEmpty) {
        return GeneratedContent(
          id: DateTime.now().millisecondsSinceEpoch.toString(),
          text: '欢迎来到直播间，精彩内容即将开始！',
          createdAt: DateTime.now(),
        );
      }
      
      // 直接返回原始文本，不做任何处理
      return GeneratedContent(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        text: description,
        createdAt: DateTime.now(),
      );
    } catch (e) {
      print('[ContentGenerator] 获取推广词失败: $e');
      // 返回默认内容
      return GeneratedContent(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        text: '精彩内容，不容错过！',
        createdAt: DateTime.now(),
      );
    }
  }
  
  Future<List<GeneratedContent>> generateBatch(int count) async {
    final contents = <GeneratedContent>[];
    for (int i = 0; i < count; i++) {
      contents.add(await generateSingleContent());
    }
    return contents;
  }
}